import React, { useEffect, useRef, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormTextArea,
  ProFormSelect,
  ProFormDateTimePicker,
  ProFormInstance
} from '@ant-design/pro-components';
import { Form, message, Modal, Progress, Slider } from 'antd';
import { useIntl, FormattedMessage, useModel,useAccess} from '@umijs/max';
import { getAssetList,getdeviceNames ,getDeviceNumsByName} from '@/services/manage/asset';
import { getTaskList } from '@/services/manage/task';

export type AlarmFormData = Record<string, unknown> & Partial<API.Manage.Alarm>;

export type AlarmFormProps = {
  onCancel: (flag?: boolean, formVals?: AlarmFormData) => void;
  onSubmit: (values: AlarmFormData) => Promise<void>;
  open: boolean;
}

const AlarmForm: React.FC<AlarmFormProps> = (props) => {
  const {onCancel, onSubmit, open} = props;
  const [form] = Form.useForm();
  // const [deviceNums, setDeviceNums] = useState<{ label: string; value: string }[]>([]);  
  const [taskNames, setTaskNames] = useState<{ label: string; value: string }[]>([]);
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 
  const [deviceNums, setDeviceNums] = useState<string[]>([]);
  const [deviceNames, setDeviceNames] = useState<string[]>([]);
  const access = useAccess();
  
 //获取设备名称
   const allDeviceNames = async () =>{
     try{
       if(access.hasPerms('inspection:asset:allDeviceName')){
         const deviceNames = await getdeviceNames();
         const deviceNameList = Array.isArray(deviceNames?.rows) ? deviceNames.rows : [];
         setDeviceNames(deviceNameList);
       }
     }
     catch(error){
       message.error('获取设备名称失败:');
       setDeviceNames([]);
     }
   }
 // 获取任务名称
const getTaskNames = async () => {
    try {
      if(access.hasPerms('inspection:taskDetail:list')){
        const tasks = await getTaskList();
        const taskList = Array.isArray(tasks?.rows)
          ? tasks.rows.map((item) => ({
              label: item.taskName,
              value: item.taskName,
            }))
          : [];
        setTaskNames(taskList);
      }
    } catch (error) {
      console.error('获取任务失败:', error);
      setTaskNames([]); // 设置为空数组防止后续组件出错
      message.error('获取任务失败');
    }
  };
  useEffect(() => {
    form.resetFields();
    allDeviceNames();
    getTaskNames();
  }, [form, props]);



  const handleFinish = async (values: Record<string, any>) => {

    const AlarmFormData = {
      ...values,
      processStatus: 0, // 默认未处理
      processor: '', // 默认处理人为空
      processTime: '', // 默认处理时间为空
      userId: currentUser?.userId,
    }
    console.log(AlarmFormData);
    onSubmit(AlarmFormData); // 提交表单数据
  };

  return (
    <Modal
      width={640}
      title='新增告警'
      forceRender
      open={open}
      onOk={()=>form.submit()} // 触发表单提交
      onCancel={()=>onCancel()} // 关闭模态框
    >
      <ProForm
        form={form}
        grid={true}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish} // 处理表单提交
        initialValues={{
          date: Date.now(),
          time: Date.now(),
        }}
        >
        <ProFormSelect
          name="deviceName"
          label='设备名称'
          options={deviceNames}
          placeholder="请选择设备名称"
          rules={[{ required: true, message: '请选择设备名称!' }]}
          onChange={async (value: string | undefined) => {
              if (value && access.hasPerms('inspection:asset:deviceNums')) {
                const deviceNum = await getDeviceNumsByName(value);
                setDeviceNums(deviceNum?.rows);
              } else {
                // 清空设备编号选项和字段值
                setDeviceNums([]);
                form.setFieldsValue({ deviceNum: undefined });
              }
          }}
        />
        <ProFormSelect
          name="deviceNum"
          label='设备编号'
          placeholder="请输入设备编号"
          options={deviceNums}
          rules={[
            {
              required: true,
              message: "请输入设备编号!",
            },           
          ]}
        />
        <ProFormRadio.Group
          // valueEnum={alarmLevel}//alarmLevel键必须为string类型
          name="alarmLevel"
          options={[
            { label: '严重', value: 1 },
            { label: '中等', value: 2 },
            { label: '轻度', value: 3 },
          ]}
          label='告警等级'
          placeholder="请选择告警等级"
          rules={[
            {
              required: true,
              message: "请选择告警等级！",
            },
          ]}
          fieldProps = {{
            defaultValue: "3"
          }}
        /> 
         <ProFormSelect
          name="taskName"
          label='巡检任务'//巡检任务ID
          options={taskNames}
          placeholder="请选择巡检任务"
          rules={[{ required: true, message: '请选择巡检任务!' }]}
        />
        <ProFormTextArea
          name="content"
          label='告警内容'
          placeholder="请输入告警内容"
          rules={[
            {
              required: true,
              message: "请输入告警内容!",
            },
          ]}
        />
        <ProFormDateTimePicker
          name="alarmTime"
          label="告警时间"
          fieldProps={{
            format: 'YYYY-MM-DD HH:mm:ss',  // 可自定义时间格式
            showTime: true,
          }}
          rules={[
            {
              required: true,
              message: "请选择告警时间！",
            },
          ]}
        /> 
      </ProForm>
    </Modal>
  );
};

export default AlarmForm;